<?php

namespace app\api\controller;

use app\facade\Redis;
use think\Validate;
use app\facade\Mns;
use app\models\{Region, PlatClass, Reimburs, Banner, Goods, Businessxq, Business, GoodsSpec, Wechat, Config, Pgoods, PgoodsSpec, Porder, PorderGoods, Address, User as Users, Order};
use think\facade\Env;
use think\Db;
use oss\Oss;
use think\db\Where;
use EasyWeChat\Factory;


class Other extends Base
{


    //任务列表
    public function orderlists()
    {
        $data = $this->request->get();
        $page = $data['page'] ?? 1;
        $limit =  $data['limit'] ?? 5;
        $page = (int)$page;
        $limit = (int)$limit;
        $lat = (float)$this->request->get('lat', 0) ?? 0;
        $lng = (float)$this->request->get('lng', 0) ?? 0;
        if (!empty($lat) && !empty($lng)) {
            if ($lat != 'undefined' && $lng != 'undefined') {
                Redis::zAdd('getlatlonarrs' . $this->request->user_id, time(), $lng . ',' . $lat);
            }
        }
        $where = [];
        $where1 = [];
        $where2 = [];
        $where[] = ['old', 'in', [2, 3]];
        $where[] = ['status', 'in', [1, 2, 3, 4]];

        if (!empty($data['status'])) {
            $sorts = ['schedule' => 'asc', 'times' => 'desc', 'created' => 'desc'];
            if ($data['status'] == 99) {
                $where[] = ['schedule', '=', 2];
                $where[] = ['xcreated', '<=', date('Y-m-d', time() - 15 * 86400)];
                $sorts = ['xcreated' => 'desc'];
            } elseif ($data['status'] == 98) {
                $where[] = ['schedule', 'in', [2, 3, 4, 5, 6]];
                $sorts = ['xcreated' => 'desc'];
            } else {
                $where[] = ['schedule', '=', $data['status']];
            }
            if ($data['status'] == 1) {
                $sorts = ['xtimes' => 'asc'];
            }
            if ($data['status'] == 4) {
                $sorts = ['zhuangxiu' => 'desc', 'ishuo' => 'desc', 'isfirst' => 'desc'];
            }
        } else {
            if ($this->request->user['type'] == 2) {
                $sorts = ['ycreated' => 'desc', 'xcreated' => 'desc', 'id' => 'desc'];
            } else {
                $sorts = ['istop' => 'desc', 'xtimes' => 'desc', 'schedule' => 'asc', 'times' => 'desc', 'created' => 'desc'];
            }
            $where[] = ['schedule', 'in', [1, 2, 3, 4, 5, 6]];
        }
        switch ($this->request->user['type']) {
            case '1':
                $where[] = ['yuid', '=', $this->request->user_id];
                break;
            case '2':
                break;
            case '3':
                $where[] = ['suid', '=', $this->request->user_id];
                break;
            case '4':
                break;
            case '5':
                break;
            case '6':
                $where[] = ['schedule', 'in', [3, 4, 5]];
                $where[] = ['ordertype', 'in', [1, 2, 3, 4, 5, 11]];
                $where[] = ['ctype', 'in', [1]];
                break;
            default:
                $this->result([], 0, '无权限');
                break;
        }
        if (!empty($data['daterange'])) {
            $range = explode(',', $data['daterange']);
            if (count($range) < 2) {
                $where[] = ['created', 'between time', []];
            } else {
                $where[] = ['created', 'between time', [$range[0], $range[count($range) - 1]]];
            }
        }
        if (!empty($data['weikuan'])) {
            $where[] = ['weikuan', '=', $data['weikuan']];
        }
        if (!empty($data['typeid'])) {
            $where[] = ['type', '=', $data['typeid']];
        }
        if (!empty($data['huojia'])) {
            $where[] = ['ishuo', '=', $data['huojia']];
        }
        if (!empty($data['shoudan'])) {
            $where[] = ['isfirst', '=', $data['shoudan']];
        }
        if (!empty($data['zhaungxiu'])) {
            $where[] = ['zhuangxiu', '=', $data['zhaungxiu']];
        }
        if (!empty($data['shanghuo'])) {
            $where[] = ['shanghuo', '=', $data['shanghuo']];
        }
        if (!empty($data['anzhuang'])) {
            $where[] = ['huozhuang', '=', $data['anzhuang']];
        }
        if ($this->request->user_id == 261) {
            $where[] = ['duid', '>', 0];
        }
        $where2 = $where;
        if ($this->request->user['type'] == 2) {
            $where[] = ['duid|kuid', '=', $this->request->user_id];
        }
        $where1 = $where;
        //合并查询协选
        $xxser1 = [];
        $xxser2 = [];
        if (!empty($data['keywords'])) {
            $where[] = ['title|name|name2|phone2|phone|address|getaddress|province|city|area|areas', 'like', '%' . $data['keywords'] . '%'];
            //查询对应的负责人ID
            $users = (new Users())->where('account|mobile', 'like', '%' . $data['keywords'] . '%')->column('id') ?? [];
            if (count($users) > 0) {
                $where1[] = ['yuid|suid|duid|kuid', 'in', $users];
                $eeorderid = (new Businessxq())->where(['user_id' => $users, 'type' => 1])->column('orderid') ?? [];
                if (count($eeorderid) > 0) {
                    $xxser1 = $eeorderid;
                }
            } else {
                $where1[] = ['title|name2|phone2|name|phone|address|getaddress|province|city|area|areas', 'like', '%' . $data['keywords'] . '%'];
                $where2[] = ['title|name2|phone2|name|phone|address|getaddress|province|city|area|areas', 'like', '%' . $data['keywords'] . '%'];
            }
        }
        if ($this->request->user['type'] = 2) {
            $xxser2 = (new Businessxq())->where(['user_id' => $this->request->user_id, 'type' => 1])->column('orderid') ?? [];
            $xorderid = array_merge($xxser1, $xxser2);
            if (count($xorderid) > 0) {
                $where2[] = ['id', 'in', $xorderid];
            } else {
                $where2[] = ['id', 'in', [0]];
            }
        }
        $result = (new Business())->limit($limit)
            ->page($page)->order($sorts)
            ->whereOr(function ($query) use ($where) {
                $query->where($where);
            })->whereOr(function ($query) use ($where1) {
                $query->where($where1);
            })->whereOr(function ($query) use ($where2) {
                $query->where($where2);
            })->select();
        foreach ($result as $k => $shop) {
            $shop['dingorxuan'] = $shop['ordertype'];
            if ($this->request->user['type'] != 2) {
                $shop['ytypes_text'] = config()["config"]['ytypes'][$shop['ytypes']] ?? '';
            }
            if ($shop['qktype'] > 0) {
                $shop['jntype_text'] = config()["config"]['jntype'][$shop['qktype']] ?? '';
            }
            $shop['ytypeslist_text'] = config()["config"]['ytypeslist'][$shop['ytypeslist']] ?? '';
            $shop['schedule_text'] = config()["config"]['schedule_text'][$shop['schedule']] ?? '';
            $shop['ordertype_text'] = config()["config"]['ordertype'][$shop['ordertype']] ?? '类型待定';
            if ($shop['ordertype'] == 3 && $shop['ctype'] == 2) {
                $shop['ordertype_text'] = '二次测量';
            }
            //售后经理信息
            $shouhou = (new Users())->where('id', $shop['suid'])->find();
            $shop['shouhuo'] = $shouhou['account'] ?? '无'; //售后经理
            $shop['shouhuo_mobile'] = $shouhou['mobile'] ?? ''; //售后经理电话
            //选址督导信息
            $dudao = (new Users())->where('id', $shop['duid'])->find();
            $shop['dudao'] = $dudao['account'] ?? '无'; //选址督导
            $shop['dudao_mobile'] = $dudao['mobile'] ?? ''; //选址督导电话
            //业务经理信息
            $yewu = (new Users())->where('id', $shop['yuid'])->find();
            $shop['yewu'] = $yewu['account'] ?? '无'; //业务经理
            $shop['yewu_mobile'] = $yewu['mobile'] ?? ''; //业务经理电话
            //开业督导信息
            $kaiye = (new Users())->where('id', $shop['kuid'])->find();
            $shop['kaiye'] = $kaiye['account'] ?? '无'; //开业督导
            $shop['kaiye_mobile'] = $kaiye['mobile'] ?? ''; //开业督导电话
            $shop['type_name'] = config()["config"]['type'][$shop['type']] ?? '';
            $shop['images'] = json_decode($shop['images'] ?? '', true) ?? [];
            $shop['images1'] = json_decode($shop['images1'] ?? '', true) ?? [];
            $shop['images2'] = json_decode($shop['images2'] ?? '', true) ?? [];
            $shop['images3'] = json_decode($shop['images3'] ?? '', true) ?? [];
            $shop['images4'] = json_decode($shop['images4'] ?? '', true) ?? [];
            $shop['images5'] = json_decode($shop['images5'] ?? '', true) ?? [];
            $shop['images6'] = json_decode($shop['images6'] ?? '', true) ?? [];
            $shop['images7'] = json_decode($shop['images7'] ?? '', true) ?? [];
            $shop['images9'] = json_decode($shop['images9'] ?? '', true) ?? [];
            $shop['images10'] = json_decode($shop['images10'] ?? '', true) ?? [];
            $shop['video'] = json_decode($shop['video'] ?? '', true) ?? [];
            $shop['video1'] = json_decode($shop['video1'] ?? '', true) ?? [];
            $shop['xxlist'] = []; //协选人员列表
            $xxlist = [];
            //协选人员
            $xxhave = (new Businessxq())->where(['orderid' => $shop['id'], 'type' => 1])->column('user_id') ?? [];
            if (count($xxhave) > 0) {
                foreach ($xxhave as $ks => $xxuser) {
                    $xxusers = (new Users())->where('id', $xxuser)->find();
                    if (!empty($xxusers)) {
                        $xxlist[] = $xxusers['account'] ?? '';
                    }
                }
            }
            $shop['xxlist'] = $xxlist; //协选人员列表
            //仓库确认发货入口
            $shop['ckcan'] = 0;
            if ($this->request->user['type'] == 6 && $shop['ishuo'] == 2 && $shop['isfirst'] == 2) {
                $shop['ckcan'] = 1;
            }
            //选址可报销提交次数
            $shop['dcan'] = 0;
            //开业可报销提交次数
            $shop['kcan'] = 0;
            if ($this->request->user['type'] == 2) {
                $fxhave = (new Businessxq())->where(['user_id' => $this->request->user_id, 'orderid' => $shop['id'], 'type' => 1])->count() ?? 0;
                //选址是否已提交报销
                if ($shop['schedule'] >= 2 && ($shop['duid'] == $this->request->user_id || $fxhave > 0)) {
                    $ll = (new Reimburs())->where(['orderid' => $shop['id'], 'old' => 1, 'user_id' => $this->request->user_id, 'status' => [1, 2], 'type' => 1])->count();
                    if ($ll <= 0) {
                        $shop['dcan'] = 1;
                    }
                }
                //开业是否已提交报销
                if ($shop['schedule'] >= 5 && $shop['kuid'] == $this->request->user_id) {
                    $ll = (new Reimburs())->where(['orderid' => $shop['id'], 'old' => 1, 'user_id' => $this->request->user_id, 'status' => [1, 2], 'type' => 2])->count();
                    if ($ll <= 0) {
                        $shop['kcan'] = 1;
                    }
                }
                //到了开业步骤的单隐藏部分备注
                if ($shop['schedule'] >= 3) {
                    $shop['yremark'] = '';
                    $shop['dremark'] = '';
                    $shop['xremark'] = '';
                    $shop['xuanzhirmeark'] = '';
                }
            }
            $shop['xcolor'] = 1;
            if (empty($shop['xtimes']) && $shop['schedule'] >= 1 && $shop['schedule'] < 3) {
                $shop['xtimes'] = '待定';
                $shop['xcolor'] = 2;
            }
            // if($shop['duid'] == $this->request->user_id && $shop['kuid'] != $this->request->user_id && $shop['type'] == 2){
            //     unset($result[$k]);
            // }
        }
        //售后经理
        $dudao = (new Users())->where(['type' => 2, 'del' => 1])->field('id,account as name,del')->select();
        foreach ($dudao as $peoples) {
            if ($peoples['del'] == 2) {
                $peoples['name'] = $peoples['name'] . '(账号已删除)';
            }
        }
        //派单类型
        $ordertypelist = []; //全款类型
        $ordertype = config('config.ordertype');
        foreach ($ordertype as $k => $v) {
            $ordertypelist[] = ['id' => $k, 'name' => $v];
        }
        //计总
        $allnumber = (new Business())->whereOr(function ($query) use ($where) {
            $query->where($where);
        })->whereOr(function ($query) use ($where1) {
            $query->where($where1);
        })->whereOr(function ($query) use ($where2) {
            $query->where($where2);
        })->count();
        $this->result(['data' => $result, 'dudao' => $dudao, 'allnumber' => $allnumber, 'ordertypelist' => $ordertypelist], 0, '获取成功');
    }

    public function getoss()
    {
        $config = config('wechat2.');
        $app = Factory::officialAccount($config);
        $accessToken = $app->access_token;
        $token = $accessToken->getToken(); // token 数组  token['access_token'] 字符串
        $data = [
            'action_name' => 'QR_LIMIT_STR_SCENE',
            "action_info" =>  ["scene" => ["scene_id" =>  123]]
        ];
        $data = json_encode($data, true);
        dump($data);
        $result = api_curl('https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=' . $token['access_token'], $data, 1);
        dump($result);
        die;
        $oss = new Oss();
        $oss->setUploadType('ram');
        $data = $oss->getCredentials();
        $data['regionId'] = Env::get('aliyun.regionId');
        $data['bucket'] = Env::get('aliyun.bucket');
        $data['endpoint'] = Env::get('aliyun.endpoint');
        $this->result($data, 0, '获取成功');
    }

    public function getopenid()
    {
        $data = $this->request->get();
        $validate = new Validate([
            'userid' => 'require',
            'code' => 'require'
        ], [
            'userid.require' => '账号不能为空',
            'code.require' => 'code必须填写',
        ]);
        if (!$validate->check($data)) {
            $results = ['status' => 1, 'info' => $validate->getError()];
            return view(null, ['list' => $results]);
        }
        $users = (new Users())->where('id', $data['userid'])->find();
        if (empty($users)) {
            $results = ['status' => 1, 'info' => '授权失败,用户不存在'];
            return view(null, ['list' => $results]);
        }
        // if (!empty($users['openid'])){
        //     $results = ['status' => 1, 'info' => '您已授权,无需重复授权'];
        //     return view(null, ['list' => $results]);
        // }
        $config = config('wechat2.');
        try {
            $app = Factory::officialAccount($config);
            $result = $app->oauth->user();
            $user = $app->user->get($result['id']);
            if($data['userid'] == 108){
                dump($user);
            }
            if (empty($user['subscribe']) || $user['subscribe'] != 1) {
                return view(null, ['list' => ['status' => 1, 'info' => '授权前请先关注[烘焙好忙服务号]公众号!']]);
            }
            if ($users['openid'] == $result['id']) {
                $res = true;
            } else {
                $res = (new Users())->where('id', $users['id'])->update(['openid' => $result['id'], 'old' => 2]);
            }
            if (!$res) {
                $results = ['status' => 1, 'info' => '授权失败,请重试'];
                return view(null, ['list' => $results]);
            }
            $results = ['status' => 0, 'info' => '账号【' . $users['account'] . '】授权成功，已订阅公众号订单通知服务!'];
            return view(null, ['list' => $results]);
        } catch (\Exception $e) {
            $results = ['status' => 1, 'info' => $e->getMessage()];
            return view(null, ['list' => $results]);
        }
        $results = ['status' => 1, 'info' => '授权失败,请重试'];
        return view(null, ['list' => $results]);
    }

    public function pgoods()
    {
        $data = $this->request->get();
        $result = (new Pgoods())->order('sale desc')->field('id,images,title,descs');
        if (!empty($data['title'])) {
            $result = $result->where('title|keywords', 'like', '%' . $data['title'] . '%');
        }
        $result = $result->where(['isdel' => 1, 'isSale' => 1])->paginate(20, false, ['query' => $this->request->param()]);
        foreach ($result as $results) {
            $results['images'] = json_decode($results['images'], true);
            $results['spec'] = (new PgoodsSpec())->where(['goodid' => $results['id'], 'isdel' => 1])->order('is_default desc')->field('id,name,price,unmit')->select();
        }
        $this->result($result, 0, '获取成功');
    }

    public function getpgoodsdetail()
    {
        $id  = $this->request->get('id/d', '0');
        $result = (new Pgoods())->where(['id' => $id, 'isdel' => 1])->field('id,title,images,sale,isSale,descs,goodsDesc')->find();
        if ($result) {
            $result['images'] = json_decode($result['images'], true);
            $result['sku'] = 0;
            $spec = (new PgoodsSpec())->where(['goodid' => $result['id'], 'isdel' => 1])->order('is_default desc')->field('id,name,price,unmit,stock')->select();
            $result['spec'] = $spec;
            foreach ($spec as $specs) {
                $result['sku'] += $specs['stock'];
            }
        }
        $this->result($result, 0, '获取成功');
    }

    public function putporder()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'specid' => 'require',
            'addressid' => 'require'
        ], [
            'specid.require' => '规格ID不能为空',
            'addressid.require' => '地址ID不能为空',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $data['specid'] = json_decode($data['specid'] ?? '', true);
        if (empty($data['specid'])) {
            $this->result([], 1, '规格数据错误');
        }
        //查询地址是否存在
        $address = (new Address())->where(['user_id' => $this->request->user_id, 'id' => $data['addressid']])->find();
        if (empty($address)) {
            $this->result([], 1, '地址信息错误存在');
        }
        $order = [
            'user_id' => $this->request->user_id,
            'ordersn' => reordersn(new Porder()),
            'name' => $address['name'],
            'mobile' => $address['mobile'],
            'province' => $address['province'],
            'city' => $address['city'],
            'area' => $address['area'],
            'getaddress' => $address['getaddress'],
            'address' => $address['address'],
            'lat' => $address['lat'],
            'lon' => $address['lon'],
            'total' => 0,
            'remark' => $data['remark'] ?? '',
            'paytimes' => date('Y-m-d H:i:s'),
            'total' => 0,
            'status' => 2,
            'ptotal' => 0
        ];
        $ordergoods = [];
        foreach ($data['specid'] as $spec) {
            if (empty($spec['id'])  || empty($spec['number'])) {
                $this->result([], 1, '规格参数错误');
            }
            //查询规格是否存在
            $goodspec = (new PgoodsSpec())->where(['isdel' => 1, 'id' => $spec['id']])->find();
            if (empty($goodspec)) {
                $this->result([], 1, '规格已下架，请重新提交订单');
            }
            //判断商品是否下架
            $goods = (new Pgoods())->where(['isdel' => 1, 'isSale' => 1, 'id' => $goodspec['goodid']])->find();
            if (empty($goods)) {
                $this->result([], 1, '商品已下架');
            }
            if ($goodspec['stock'] < $spec['number']) {
                $this->result([], 1, '库存不足');
            }
            //查找下面有没有相关服务人员
            $order['ptotal'] += $goodspec['price'] * $spec['number'];
            $ordergoods[] = [
                'ordersn' => $order['ordersn'],
                'goodsid' => $goods['id'],
                'goodspecid' => $goodspec['id'],
                'title' => $goods['title'],
                'images' => $goods['images'],
                'name' => $goodspec['name'],
                'number' =>  $spec['number'],
                'unmit' => $goodspec['unmit'],
                'price' =>   $goodspec['price'],
                'total' => floor($spec['number'] * $goodspec['price'] * 100) / 100
            ];
        }
        $order['total'] = $order['ptotal'];
        if (count($ordergoods) < 1 || count($order) < 1) {
            $this->result([], 1, '结算出错,请重试');
        }
        if ($this->request->user['intergal'] < $order['total']) {
            $this->result([], 1, '积分不足，无法兑换');
        }
        Db::startTrans();
        try {
            (new Users())->MoneyEdit($this->request->user_id, 2, -$order['total'], '兑换商品扣除', $order['ordersn']);
            $id = (new Porder())->insertGetId($order);
            (new PorderGoods())->allowfield(true)->saveAll($ordergoods);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->result([], 1, '下单失败');
        }
        $this->result(['id' => $id], 0, '下单成功');
    }

    public function porderlist()
    {
        $status = $this->request->get('status/d', '');
        $list = (new Porder())->order('id desc');
        if (!empty($status)) {
            $list = $list->where('status', $status);
        }
        $list = $list->where('user_id', $this->request->user_id)->field('id,ordersn,status,total,created')->paginate(20, false, ['query' => $this->request->param()]);
        foreach ($list as $lists) {
            $ordergoods = (new PorderGoods())->where(['ordersn' => $lists['ordersn']])->field('id,title,name,unmit,goodspecid,images,number,goodsid,price')->select();
            foreach ($ordergoods as $goods) {
                $goods['images'] = json_decode($goods['images'] ?? '', true);
            }
            $lists['goods'] = $ordergoods;
            $lists['status_text'] = $lists->status_text;
        }
        $this->result($list, 0, '获取成功');
    }

    public function porderdetail()
    {
        $id = $this->request->get('id/d', 0);
        $list = (new Porder())->where('id', $id)->field('payment', true)->find();
        if ($list) {
            $list['status_text'] = $list->status_text;
            $goods = (new PorderGoods())->where('ordersn', $list['ordersn'])->field('id,ordersn,images,number,title,name,goodsid,goodspecid,price,unmit')->select();
            foreach ($goods as $good) {
                $good['images'] = json_decode($good['images'], true);
            }
            $list['good'] = $goods;
        }
        $this->result($list, 0, '获取成功');
    }


    public function getstreet()
    {
        $key = env('map.key');
        if ($this->request->isGet()) {
            $data = $this->request->get();
            $validate = new Validate([
                'lat' => 'require',
                'lng' => 'require',
            ], [
                'lat.require' => '纬度必须填写',
                'lng.require' => '经度必须填写',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $url = 'https://restapi.amap.com/v3/geocode/regeo';
            $res = api_curl($url, ['location' => $data['lng'] . ',' . $data['lat'], 'key' => $key, 'extensions' => 'all']);
            if ($res['status'] == 1) {
                if (empty($res['regeocode']['addressComponent'])) {
                    $this->result([], 1, '请求失败');
                }
                $results = $res['regeocode']['addressComponent'];
                $resuls = [
                    "adcode" => $results['adcode'] ?? 0,
                    "province" => $results['province'] ?? '',
                    "city" => $results['city'] ?? '',
                    "district" => $results['district'] ?? '',
                    "street_title" => $results['township'] ?? '',
                    'address' => $res['regeocode']['aois'][0]['name'] ?? ($res['regeocode']['pois']['0']['name'] ?? ""),
                    'formatted_address' => $res['regeocode']['formatted_address'] ?? ''
                ];
                if (empty($resuls['address'])) {
                    $resuls['address'] = $resuls['formatted_address'] ?? '';
                }
                $resuls['city'] = empty($resuls['city']) ? $resuls['province'] : $resuls['city'];
                $this->result($resuls, 0, '获取成功');
            } else {
                $this->result([], 1, '请求失败');
            }
        } else {
            $this->result([], 0, ['key' => $key]);
        }
    }

    public function others()
    {
        $name = $this->request->get('name', '');
        $result = (new Config())->where('name', $name)->value('value') ?? '';
        $this->result($result, 0, '获取成功');
    }

    //支付回调结果
    public function callback()
    {

        $result = (new Wechat())->callback();
        if ($result['msg'] == 'success') {
            return true;
        }
        return false;
    }

    //取消订单回调结果
    public function callback2()
    {
        $result = (new Wechat())->callback2();
        if ($result['msg'] == 'success') {
            return true;
        }
        return false;
    }


    public function oss()
    {

        if ($this->request->isPost()) {
            $file = request()->file('file');
            if (empty($_FILES['file'])) {
                $this->result([], 1, '参数错误');
            }
            $path =  $_SERVER['DOCUMENT_ROOT'] . "/uploads/";
            $info = $file->validate(['size' => 1024 * 1024 * 200000000000])
                ->move($path);
            if (!$info) {
                $this->result([], 1, $file->getError());
            } else {
                $url = '/uploads' . '/' . date("Ymd") . '/' . $info->getfileName();
                $url = url($url, '', '', false);
                $url = "https://" . Env('app.api_url') . $url;
                $this->result(['url' => $url], 0, '获取成功');
            }
        } else {
            $this->result([], 1, '请求错误');
        }
    }

    public function addressjson()
    {
        $addressjsonredis = 'addressjsonredis';
        $haveaddress = Redis::get($addressjsonredis);
        if ($haveaddress) {
            $result = unserialize($haveaddress);
        } else {
            $region = (new Region())->field('name as label,area_code as value,id,parent_id,level,shenhui')->where(['level' => [1, 2, 3]])->select();
            $resultson = [];
            $results = [];
            $result = [];
            foreach ($region as $regions) {
                if ($regions['level'] == 3) {
                    $resultson[$regions['parent_id']][] = [
                        'label' => $regions['label'],
                        'value' => $regions['value']
                    ];
                }
            }
            foreach ($region as $regions) {
                if ($regions['level'] == 2) {
                    if ($regions['shenhui'] == 2) {
                        array_unshift($resultson[$regions['id']], [
                            'label' => '不选择',
                            'value' => 0
                        ]);
                    }
                    $results[$regions['parent_id']][] = [
                        'label' => $regions['label'],
                        'value' => $regions['value'],
                        'children' => $resultson[$regions['id']] ?? []
                    ];
                }
            }
            foreach ($region as $regions) {
                if ($regions['level'] == 1) {
                    $result[] = [
                        'label' => $regions['label'],
                        'value' => $regions['value'],
                        'children' => $results[$regions['id']] ?? []
                    ];
                }
            }
            Redis::setex($addressjsonredis, 60 * 60 * 3, serialize($result));
        }
        return json($result);
    }

    public function banner()
    {
        $lon  = $this->request->get('lon/f', '0');
        $lat  = $this->request->get('lat/f', '0');
        $filed = 'ROUND(6378.138*2*ASIN(SQRT(POW(SIN((' . $lat . '*PI()/180-lat*PI()/180)/2),2)+COS(' . $lat . '*PI()/180)*COS(lat*PI()/180)*POW(SIN((' . $lon . '*PI()/180-lon*PI()/180)/2),2)))*100)/100 AS dist';
        $business = (new Business())
            ->field('id,title,sendkm,' . $filed)
            ->order('dist asc')
            ->having('dist <= sendkm')
            ->select();
        $businessid = array_column($business->toArray(), 'id') ?? [];
        $businessid[] = 0;
        $result = (new Banner())->where(['business' => $businessid])->field('title,id,business,url')->select();
        $this->result($result, 0, '获取成功');
    }


    public function getopenid111()
    {
        $data = $this->request->get();
        $validate = new Validate([
            'mobile' => 'require',
            'code' => 'require'
        ], [
            'mobile.require' => '账号不能为空',
            'code.require' => 'code必须填写',
        ]);
        if (!$validate->check($data)) {
            $results = ['status' => 1, 'info' => $validate->getError()];
            return view(null, ['list' => $results]);
        }
        $business = (new Business())->where('account', $data['mobile'])->find();
        if (empty($business)) {
            $results = ['status' => 1, 'info' => '授权失败,商家不存在'];
            return view(null, ['list' => $results]);
        }
        $config = config('wechat2.');
        try {
            $app = Factory::officialAccount($config);
            $result = $app->oauth->user();
            if ($business['wopenid'] == $result['id']) {
                $res = true;
            } else {
                $res = (new Business())->where('id', $data['id'])->update(['wopenid' => $result['id']]);
            }
            if (!$res) {
                $results = ['status' => 1, 'info' => '授权失败,请重试'];
                return view(null, ['list' => $results]);
            }
            $data = [
                'first' => [
                    'value' => '这是一个测试订消息'
                ],
                'keyword1' => [
                    'value' => time()
                ],
                'keyword2' => [
                    'value' =>  date('Y-m-d H:i:s')
                ],
                'keyword3' => [
                    'value' => '张三'
                ],
                'keyword4' => [
                    'value' =>  "北京市东城区老李胡同"
                ],
                'remark' => [
                    'value' => "请尽快配货进行服务喔"
                ]
            ];
            (new Order())->message($result['id'], 'mDgUsTS1E5HZBWcijYhQZMYiROSjA3j8j4XmLVld8ns', $data, config('wechat.')['app_id'], '/');
            $results = ['status' => 0, 'info' => '授权成功，您已订阅公众号订单通知服务!'];
            return view(null, ['list' => $results]);
        } catch (\Exception $e) {
            $results = ['status' => 1, 'info' => $e->getMessage()];
            return view(null, ['list' => $results]);
        }
        $results = ['status' => 1, 'info' => '授权失败,请重试'];
        return view(null, ['list' => $results]);
    }
}
